package com.crane.app.web.controller;


import com.crane.common.core.dto.MultiResponse;
import com.crane.common.core.dto.Response;
import com.crane.common.core.dto.SingleResponse;
import com.crane.common.core.utils.BaseContextHandler;
import com.crane.common.framework.utils.Jackson2JsonUtil;
import com.crane.oss.app.bean.request.mqtt.BaseRopeInfo;
import com.crane.oss.app.bean.request.mqtt.UpdateModeResp;
import com.crane.oss.app.bean.request.mqtt.UpdateMusicModeReq;
import com.crane.oss.app.bean.request.mqtt.UpdateSkipModeReq;
import com.crane.oss.app.service.AppMqttApi;
import com.crane.oss.app.service.AppUserService;
import com.crane.oss.school.bean.request.student.AppUpdateStudentReq;
import com.crane.oss.school.bean.resp.StudentResp;
import com.crane.oss.school.service.StudentEquipmentService;
import com.crane.oss.school.service.StudentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @author bealon
 */
@Api(value = "AppMqttController", tags = {"消息推送"})
@RestController
@RequestMapping("/app/mqtt")
public class AppMqttController {

    public static final String TOPIC="longcos_";

    private static final Logger logger = LoggerFactory.getLogger(AppMqttController.class);

    @Resource
    AppMqttApi appMqttApi;

    @Resource
    StudentEquipmentService studentEquipmentService;

    @Autowired
    AppUserService appUserService;

    @Resource
    StudentService studentService;

    @ApiOperation(value = "绑定设备", notes = "绑定设备")
    @ApiImplicitParam(name = "request", value = "请求对象", required = true, dataType = "BaseRopeInfo")
    @PostMapping("/bindRope")
    public Response bindRope(@RequestBody @Valid BaseRopeInfo request) {
        Long userId= BaseContextHandler.getUserId();
        StudentResp studentResp=appUserService.getDefaultStudent(userId);
        if(null == studentResp){
            return SingleResponse.buildFailure("未绑定学生");
        }
        Response response=studentEquipmentService.bindEquiment(studentResp.getStudentId(),request.getImei());
        if(response.isSuccess()){
            appMqttApi.sendToMqtt("{\"cmd\":\"MANAGER_BIND_SUCCESS\"}",AppMqttController.TOPIC+request.getImei());
        }
        return response;
    }

    @ApiOperation(value = "解绑设备", notes = "解绑设备")
    @ApiImplicitParam(name = "request", value = "请求对象", required = true, dataType = "BaseRopeInfo")
    @PostMapping("/unbindRope")
    public Response unbindRope(@RequestBody @Valid BaseRopeInfo request) {
        Long userId= BaseContextHandler.getUserId();
        StudentResp studentResp=appUserService.getDefaultStudent(userId);
        if(null == studentResp){
            return SingleResponse.buildFailure("未绑定学生");
        }
        Response response=studentEquipmentService.unBindEquiment(studentResp.getStudentId(),request.getImei());
        if(response.isSuccess()){
            appMqttApi.sendToMqtt("{\"cmd\":\"UNBIND_SUCCESS\"}",AppMqttController.TOPIC+request.getImei());
        }
        return response;
    }

    @ApiOperation(value = "设置音乐模式", notes = "设置音乐模式")
    @ApiImplicitParam(name = "request", value = "请求对象", required = true, dataType = "UpdateMusicModeReq")
    @PostMapping("/musicMode")
    public Response musicModeRope(@RequestBody @Valid UpdateMusicModeReq request) {
        Long userId= BaseContextHandler.getUserId();
        StudentResp studentResp=appUserService.getDefaultStudent(userId);
        if(null == studentResp){
            return SingleResponse.buildFailure("未绑定学生");
        }
        MultiResponse<UpdateModeResp> response=studentEquipmentService.musicModeRope(studentResp.getStudentId(),request.getMusicMode());
        if(response.isSuccess()){
              for(UpdateModeResp updateModeResp : response.getData().getList()){
                  if(updateModeResp.getBindType() == 1){
                      Map<String,Object> cmd=new HashMap<>();
                    cmd.put("cmd","SET_SKIP_MUSICMODE");
                    cmd.put("musicmode",request.getMusicMode());
                    appMqttApi.sendToMqtt(Jackson2JsonUtil.toString(cmd),AppMqttController.TOPIC+updateModeResp.getImei());
                  }
              }
        }
        return response;
    }

    @ApiOperation(value = "设置跳绳模式", notes = "设置跳绳模式")
    @ApiImplicitParam(name = "request", value = "请求对象", required = true, dataType = "UpdateSkipModeReq")
    @PostMapping("/skipMode")
    public Response skipModeRope(@RequestBody @Valid UpdateSkipModeReq request) {
        Long userId= BaseContextHandler.getUserId();
        StudentResp studentResp=appUserService.getDefaultStudent(userId);
        if(null == studentResp){
            return SingleResponse.buildFailure("未绑定学生");
        }
        MultiResponse<UpdateModeResp> response=studentEquipmentService.skipModeRope(studentResp.getStudentId(),request.getSkipmode());
        if(response.isSuccess()){
            for(UpdateModeResp updateModeResp : response.getData().getList()){
                if(updateModeResp.getBindType() == 1){
                    Map<String,Object> cmd=new HashMap<>();
                    cmd.put("cmd","SET_SKIP_MODE");
                    cmd.put("taskid",request.getTaskId());
                    cmd.put("skipmode",request.getSkipmode());
                    appMqttApi.sendToMqtt(Jackson2JsonUtil.toString(cmd),AppMqttController.TOPIC+updateModeResp.getImei());
                }
            }
        }
        return response;
    }


    @ApiOperation(value = "修改体重", notes = "修改体重")
    @ApiImplicitParam(name = "request", value = "请求对象",  dataType = "AppUpdateStudentReq")
    @PostMapping("/updateWeight")
    public Response updateWeight(@RequestBody AppUpdateStudentReq request) {
        SingleResponse<UpdateModeResp> response=studentService.appUpdateStudent(request);
        if(response.isSuccess() && null!= response.getData() && response.getData().getBindType() == 1){
            appMqttApi.sendToMqtt("{\"cmd\":\"MODIFY_DEVICE_INFO_CMD\"}",AppMqttController.TOPIC+response.getData().getImei());
        }
        return response;
    }

    @PostMapping("/shutdown")
    public Response shutdown(@RequestBody @Valid BaseRopeInfo request) {
        appMqttApi.sendToMqtt("{\"cmd\":\"" +
                "\"}",AppMqttController.TOPIC+request.getImei());
        return Response.buildSuccess();
    }

}
